<template>
    <div>
        {{ pageModel }}
        <el-dialog title="编辑库存"
                   :visible.sync="dialogFormVisible">
            <el-form :model="form">
                <el-form-item label="库存"
                              :label-width="formLabelWidth">
                    <el-input v-model="form.stock"
                              autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer"
                  class="dialog-footer">
        <el-button @click="cancel">Cancel</el-button>
        <el-button type="primary"
                   @click="Ok">Ok</el-button>
      </span>
        </el-dialog>
        <el-dialog title="编辑"
                   :visible.sync="dialogFormVisible1"
                   width="58%">
            <el-form id="contentForm"
                     :model="contentForm"
                     ref="contentForm"
                     :label-width="labelWidth"
                     class="inline-form"
                     :rules="rules">
                <el-form-item label="商品名称"
                              prop="goodsName">
                    <el-input v-model="contentForm.goodsName"
                              name="goodsName"></el-input>
                </el-form-item>
                <el-form-item label="商品数量"
                              prop="stock">
                    <el-input v-model.number="contentForm.stock"
                              name="stock"></el-input>
                </el-form-item>
                <el-form-item label="支付积分"
                              prop="exchangeScore">
                    <el-input v-model.number="contentForm.exchangeScore"
                              type="exchangeScore"></el-input>
                </el-form-item>
                <el-form-item label="商品类型"
                              prop="goodsType">
                    <el-select v-model="contentForm.goodsType"
                               @change="change"
                               placeholder="请选择">
                        <el-option v-for="(types,index) in selction"
                                   :value="types.gtid"
                                   :label="types.goodsTypeName"
                                   :key="index">{{types.goodsTypeName}}
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="话费"
                              prop="bill"
                              v-show="phone=='充值卡'">
                    <el-input v-model="contentForm.bill"
                              name="bill"
                              style="width: 85%;"></el-input>
                    <span>分</span>
                </el-form-item>
                <el-form-item label="使用说明" prop="instructions" v-show="phone=='电子优惠券'">
                    <quill-editor style="width: 600px;"
                                  ref="myTextEditor"
                                  @change="showChange($event)"
                                  v-model="contentForm.instructions"
                                  :options="editorDescription"></quill-editor>
                    <el-input type="hidden" v-model="contentForm.instructions"></el-input>
                </el-form-item>
                <el-form-item label="商品分享标题"
                              prop="shareTitle">
                    <el-input v-model="contentForm.shareTitle"
                              name="shareTitle"></el-input>
                </el-form-item>
                <el-form-item label="商品图片"
                              prop="imgSrc">
                    <el-upload class="avatar-uploader"
                               :action="uploadImg.action"
                               :on-remove="handleRemove"
                               :on-preview="handlePreview"
                               :on-success="handleSuccess"
                               :limit="1"
                               :before-upload="qwe"
                               :file-list="fileList"
                               list-type="picture">
                        <el-button size="small"
                                   type="primary">点击上传
                        </el-button>
                        <div slot="tip"
                             class="el-upload__tip">只能上传jpg/png文件
                        </div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="分享商品图片"
                              prop="shareImgUrl">
                    <el-upload class="avatar-uploader"
                               :action="uploadImg.action"
                               :on-remove="handleRemove1"
                               :on-preview="handlePreview1"
                               :on-success="handleSuccess1"
                               :limit="1"
                               :before-upload="qwe1"
                               :file-list="fileList1"
                               list-type="picture">
                        <el-button size="small"
                                   type="primary">点击上传
                        </el-button>
                        <div slot="tip"
                             class="el-upload__tip">只能上传300*300的jpg文件
                        </div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="日期范围"
                              required>
                    <el-date-picker style="width: 376px"
                                    v-model="msgInfoDate"
                                    type="datetimerange"
                                    range-separator="至"
                                    format="yyyy-MM-dd HH:mm:ss"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    @change="renderMsgDate"
                                    @blur="blur"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期">
                    </el-date-picker>
                    <div style="color:#f56c6c;font-size:12px;margin-bottom: -25px;"
                         v-if="dataShow">请填写日期范围
                    </div>
                </el-form-item>
                <el-form-item label="是否置顶"
                              prop="topFlag">
                    <el-radio-group name="topFlag"
                                    v-model="contentForm.topFlag">
                        <el-radio label="1">是</el-radio>
                        <el-radio label="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="砍价时间"
                              prop="bargainTime">
                    <el-input v-model.number="contentForm.bargainTime"
                              name="bargainTime"
                              placeholder="单位/时间">
                    </el-input>
                </el-form-item>
                <el-form-item label="单次砍价金额（积分）"
                              required>
                    <el-col :span="11">
                        <el-form-item prop="scoreStart">
                            <el-input v-model.number="contentForm.scoreStart"
                                      name="scoreStart"
                                      style="width:40%"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col class="line"
                            :span="2"><span>至</span></el-col>
                    <el-col :span="11">
                        <el-form-item prop="scoreEnd">
                            <el-input v-model.number="contentForm.scoreEnd"
                                      name="scoreEnd"
                                      style="width:40%"></el-input>
                        </el-form-item>
                    </el-col>
                </el-form-item>
                <el-form-item label="最低金额"
                              prop="">
                    <el-input v-model="contentForm.lowestQuotation"
                              :disabled="true">{{lowestQuotationCount}}
                    </el-input>
                </el-form-item>
                <el-form-item label="砍价次数"
                              prop="bargainNum">
                    <el-input v-model.number="contentForm.bargainNum"></el-input>
                </el-form-item>
                <el-form-item label="商品简介"
                              prop="description">
                    <quill-editor style="width: 600px;"
                                  v-model="htmlCon"
                                  ref="myTextEditor"
                                  @change="descriptionChange($event)"
                                  :options="editorOption"></quill-editor>
                    <el-input type="hidden"
                              v-model="contentForm.description"
                              name="description"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary"
                               @click="submitPrizeHandle()">确定
                    </el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <el-table :data="tableData"
                  border
                  align="center"
                  header-align="center"
                  width="150%"
                  style="text-align: center;"
                  tooltip-effect="dark">
            <el-table-column type="index"
                             width="50">
            </el-table-column>
            <el-table-column prop="egtid"
                             label="商品id"
                             width="80">
            </el-table-column>
            <el-table-column label="商品名称"
                             prop="goodsName">
            </el-table-column>
            <el-table-column label="商品图">
                <template slot-scope="scope">
                    <img :src="'/ActivityWeb/static/'+scope.row.imgSrc"
                         class="img"/>
                </template>
            </el-table-column>
            <el-table-column prop="goodsName"
                             label="商品名称"
                             v-if="doll">
            </el-table-column>
            <el-table-column prop="beginTime"
                             label="上架时间">
            </el-table-column>
            <el-table-column prop="endTime"
                             label="下架时间">
            </el-table-column>
            <el-table-column prop="stock"
                             label="库存">
            </el-table-column>
            <el-table-column prop="goodsType"
                             label="商品类型"
                             :formatter="typeFormat">
            </el-table-column>
            <el-table-column width="300"
                             label="操作">
                <template slot-scope="scope">
                    <el-button class="pan-btn green-btn"
                               @click="editReserve(scope.row, scope.$index)">编辑库存
                    </el-button>
                    <el-button class="pan-btn green-btn"
                               @click="delHandle(scope.row, scope.$index)">删除
                    </el-button>
                    <el-button class="pan-btn green-btn"
                               @click="editHandle(scope.row, scope.$index)">编辑
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="footer">
            <el-pagination layout="prev, pager, next, jumper"
                           :page-size='10'
                           :total="total"
                           :current-page.sync="currentPageNum"
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange">
            </el-pagination>
        </div>
    </div>

</template>
<script>
    import {parseTime} from '@/utils/index'
    import 'quill/dist/quill.core.css'
    import 'quill/dist/quill.snow.css'
    import 'quill/dist/quill.bubble.css'
    import {quillEditor} from 'vue-quill-editor'
    import request from '@/utils/request'

    export default {
        name: 'productList',
        props: ['json'],
        data() {
            return {
                uploadImg: {
                    action: '/activityConsole/periodicalMessage/uploadImage/'
                },
                dataShow: false,
                doll: false,
                tableData: [],
                total: 1,
                currentPageNum: 1,
                pageSize: 10,
                pageNum: 0,
                dialogFormVisible: false,
                form: {
                    stock: '',
                    id: ''
                },
                phone: '',
                formLabelWidth: '120px',
                dialogFormVisible1: false,
                contentForm: {
                    egtid: '',
                    goodsName: '',
                    stock: '',
                    exchangeScore: 10,
                    topFlag: '',
                    bargainTime: '',
                    goodsType: '',
                    endTime: '',
                    beginTime: '',
                    imgSrc: '',
                    scoreStart: 0,
                    scoreEnd: 0,
                    lowestQuotation: '',
                    bargainNum: 0,
                    description: '',
                    bill: '',
                    shareTitle: '',
                    shareImgUrl: '',
                    instructions:''
                },
                rules: {
                    goodsName: [
                        {required: true, message: '请填写商品名称', trigger: 'change'}
                    ],
                    stock: [
                        {required: true, message: '请填写商品数量', trigger: 'change'},
                        {type: 'number', message: '请填写数字', trigger: 'change'}
                    ],
                    exchangeScore: [
                        {required: true, message: '请填写支付积分', trigger: 'change'},
                        {type: 'number', message: '请填写数字', trigger: 'change'}
                    ],
                    topFlag: [
                        {required: true, message: '请填写是否置顶', trigger: 'change'}
                    ],
                    bargainTime: [
                        {required: true, message: '请填写库存', trigger: 'change'},
                        {type: 'number', message: '请填写数字', trigger: 'change'}
                    ],
                    goodsType: [
                        {required: true, message: '请填写商品类型', trigger: 'change'}
                    ],
                    endTime: [
                        {type: 'string', required: true, message: '请上传图片', trigger: 'change'}
                    ],
                    imgSrc: [
                        {required: true, message: '请上传图片', trigger: 'change'}
                    ],
                    shareImgUrl: [
                        {required: true, message: '请上传图片', trigger: 'change'}
                    ],
                    scoreStart: [
                        {required: true, message: '请填写砍价最小值', trigger: 'change'},
                        {type: 'number', message: '请填写数字', trigger: 'change'}
                    ],
                    scoreEnd: [
                        {required: true, message: '请填写砍价最大值', trigger: 'change'},
                        {type: 'number', message: '请填写数字', trigger: 'change'}
                    ],
                    lowestQuotation: [
                        {required: true, message: '请填写最低金额', trigger: 'change'},
                        {type: 'number', message: '请填写数字', trigger: 'change'}
                    ],
                    bargainNum: [
                        {required: true, message: '请填写砍价次数', trigger: 'change'},
                        {type: 'number', message: '请填写数字', trigger: 'change'}
                    ],
                    description: [
                        {required: true, message: '请填写商品简介', trigger: 'change'}
                    ],
                    shareTitle: [
                        {required: true, message: '请填写分享商品标题', trigger: 'change'}
                    ]
                },
                selction: [],
                fileList: [],
                fileList1: [],
                editorOption: {
                    placeholder: 'Hello World'
                },
                editorDescription: {
                    placeholder: '请输入使用说明'
                },
                msgInfoDate: '',
                labelWidth: '175px',
                htmlCon: '',
                htmlCon2: ''
            }
        },
        mounted() {
            this.init()
            this.select()
        },
        components: {
            quillEditor
        },
        computed: {
            pageModel: function () {
                if (this.json.pageModel === 'prizeList') {
                    console.log(123)
                    this.select()
                    const _this = this
                    request({
                        url: '/activityConsole/activityBargain/getBargainMessage',
                        method: 'get',
                        params: {
                            pageNum: _this.pageNum,
                            pageSize: 10,
                            activityId: _this.json.activityId
                        }
                    }).then(res => {
                        console.log(res)
                        if (res.status === '200') {
                            _this.tableData = res.data
                            _this.total = parseInt(res.description)
                        }
                    }).catch(err => {
                        console.log(err)
                    })
                }
            },
            lowestQuotationCount: function () {
                if (this.contentForm.exchangeScore !== '' & this.contentForm.bargainNum !== '' && this.contentForm.scoreEnd !== '') {
                    this.contentForm.lowestQuotation = parseInt(this.contentForm.exchangeScore) - (parseInt(this.contentForm.bargainNum) * parseInt(this.contentForm.scoreEnd))
                }
            }
        },
        methods: {
            change(value) {
                console.log(value)
                for (let i = 0; i < this.selction.length; i++) {
                    if (this.selction[i].gtid === value) {
                        console.log(this.selction[i].goodsTypeName)
                        this.phone = this.selction[i].goodsTypeName
                    }
                }
            },
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`)
            },
            handleCurrentChange(val) {
                console.log(val)
                this.pageNum = parseInt(val) - 1
                this.init()
            },
            init() {
                const _this = this
                //    + _this.json.activityId + '/prize'
                request({
                    url: '/activityConsole/activityBargain/getBargainMessage',
                    method: 'get',
                    params: {
                        pageNum: _this.pageNum,
                        pageSize: 10,
                        activityId: _this.json.activityId
                    }
                }).then(res => {
                    console.log(res)
                    if (res.status === '200') {
                        _this.tableData = res.data
                        _this.total = parseInt(res.description)
                    }
                    // return _this.tableData = res.data
                }).catch(err => {
                    console.log(err)
                })
            },
            showChange(event) {
                this.contentForm.instructions = event.html
            },
            cancel() {
                this.form.stock = ''
                this.form.id = ''
                this.dialogFormVisible = false
            },
            Ok() {
                console.log(123)
                var _this = this
                //   var params = {}
                console.log(_this.form)
                request({
                    url: '/activityConsole/activityBargain/updateGoodsStock/' + this.form.id,
                    method: 'post',
                    params: {
                        goodsStock: _this.form.stock
                    }
                }).then(res => {
                    console.log(res)
                    if (res.status == '200') {
                        _this.init()
                        _this.form.stock = ''
                        _this.form.id = ''
                        _this.dialogFormVisible = false
                        _this.$message({
                            type: 'success',
                            message: res.description
                        })
                    } else {
                        _this.$message({
                            type: 'fail',
                            message: res.description
                        })
                    }
                }).then(err => {
                    console.log(err)
                })
            },
            editReserve(row) {
                this.dialogFormVisible = true
                this.form.stock = row.stock
                this.form.id = row.egtid
            },
            editHandle(row) {
                console.log(row);
                this.dialogFormVisible1 = true;
                this.contentForm.goodsName = row.goodsName;
                this.contentForm.stock = row.stock;
                this.contentForm.scoreStart = row.scoreStart;
                this.contentForm.scoreEnd = row.scoreEnd;
                this.contentForm.lowestQuotation = row.lowestQuotation;
                this.contentForm.bargainNum = row.bargainNum;
                this.contentForm.exchangeScore = row.exchangeScore;
                this.contentForm.bill = row.bill;
                this.contentForm.instructions = row.instructions;
                this.contentForm.linkUrl = row.linkUrl;
                for (var i = 0; i < this.selction.length; i++) {
                    console.log(row.goodsType);
                    if (this.selction[i].symbol == row.goodsType) {
                        console.log(23123);
                        console.log(this.selction[i].goodsTypeName);
                        this.contentForm.goodsType = this.selction[i].goodsTypeName;
                        if (this.contentForm.goodsType === '充值卡') {
                            this.phone = '充值卡'
                        } else {
                            this.phone = '电子优惠券'
                        }
                    }
                }
                this.msgInfoDate = [parseTime(row.beginTime), parseTime(row.endTime)];
                this.contentForm.beginTime = row.beginTime;
                this.contentForm.endTime = row.endTime;
                this.contentForm.egtid = row.egtid;
                this.contentForm.bargainTime = row.bargainTime;
                this.htmlCon = row.description;
                this.contentForm.description = row.description;
                this.contentForm.shareTitle = row.shareTitle;
                this.contentForm.topFlag = row.topFlag.toString();
                this.contentForm.imgSrc = row.imgSrc;
                if (row.imgSrc !== '') {
                    this.fileList = [];
                    const obj = {};
                    obj.url = '/ActivityWeb/static/' + row.imgSrc;
                    this.fileList.push(obj)
                }

                this.contentForm.shareImgUrl = row.shareImgUrl
                //   var arr = []
                if (row.shareImgUrl !== '') {
                    this.fileList1 = [];
                    const obj = {};
                    obj.url = '/ActivityWeb/static/' + row.shareImgUrl
                    this.fileList1.push(obj)
                }
            },
            delHandle(row, index) {
                const _this = this;
                this.$confirm('此操作将永久删除该奖品, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    cancelButtonClass: 'green-btn pan-btn',
                    type: 'warning'
                }).then(() => {
                    request({
                        url: '/activityConsole/activityBargain/id/' + row.egtid,
                        method: 'DELETE'
                    }).then(res => {
                        if (res.deleteFlag == 'true') {
                            _this.tableData.splice(index, 1)
                        }
                        _this.$message({
                            type: 'success',
                            message: '删除成功'
                        })
                    }).catch(err => {
                        console.log(err)
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    })
                })
            },
            typeFormat(row, column) {
                const type = row[column.property]
                if (type == 'RECHARGE_CARD') {
                    return '充值卡'
                }
                if (type == 'FLOW_PACKAGE') {
                    return '流量包'
                }
                if (type == 'ELECTRONIC_COUPON') {
                    return '电子优惠券'
                }
                if (type == 'ENTITY_GIFFT') {
                    return '实物礼品'
                }
                if (type == 'THANKS_PARTICIPATE') {
                    return '谢谢参与'
                }
                if (type == 'CLUB_INTEGRAL') {
                    return '俱乐部积分'
                }
                if (type == 'QY_RECHARGE') {
                    return '权益会员直充'
                }
            },
            select() {
                const _this = this
                _this.axios({
                    url: '/activityConsole/activityBargain/getGoodsTypeSelect'
                }).then(res => {
                    console.log(res)
                    if (res.data.status === '200') {
                        _this.selction = res.data.data
                        console.log(_this.selction)
                    }
                }).catch(err => {
                    console.log(err)
                })
            },
            // renderMsgDate() {
            //   console.log(123)
            // },
            blur() {
                if (this.msgInfoDate) {
                    this.dataShow = false
                } else {
                    this.dataShow = true
                }
            },
            qwe(file) {
                const _this = this
                const b = file.type.indexOf('image') !== -1
                if (!b) {
                    _this.$message({
                        type: 'error',
                        message: '文件类型不支持'
                    })
                    return false
                }
                return true
            },
            handleRemove(file, fileList) {
                const _this = this
                console.log('handleRemove:===============================================')
                _this.fileList = fileList
            },
            handlePreview(file) {
                console.log('handlePreview:===============================================')
            },
            handleSuccess(response, file, fileList) {
                const _this = this
                console.log
                console.log('handlePreviewSuccess:===============================================')
                _this.fileList = fileList
                const arr = []
                for (var i = 0; i < fileList.length; i++) {
                    arr.push(fileList[i].response.data)
                }
                _this.contentForm.imgSrc = arr.join()
                console.log(_this.contentForm.imgSrc)
            },
            qwe1(file) {
                const _this = this
                const b = file.type.indexOf('image') !== -1
                if (!b) {
                    _this.$message({
                        type: 'error',
                        message: '文件类型不支持'
                    })
                    return false
                }
                return true
            },
            handleRemove1(file, fileList) {
                const _this = this
                console.log('handleRemove:===============================================')
                _this.fileList1 = fileList
            },
            handlePreview1(file) {
                console.log('handlePreview:===============================================')
            },
            handleSuccess1(response, file, fileList) {
                const _this = this
                console.log('handlePreviewSuccess:===============================================')
                _this.fileList1 = fileList
                const arr = []
                for (let i = 0; i < fileList.length; i++) {
                    arr.push(fileList[i].response.data)
                }
                _this.contentForm.shareImgUrl = arr.join()
                console.log(_this.contentForm.shareImgUrl)
            },
            descriptionChange(event) {
                this.contentForm.description = event.html
            },
            exchangeChange(event) {
                this.contentForm.notes = event.html
            },
            renderDate(date) {
                this.contentForm.effectiveTime = date
                this.baseForm.effectiveTime = date
            },
            renderMsgDate() {
                if (this.msgInfoDate) {
                    this.contentForm.beginTime = parseTime(this.msgInfoDate[0])
                    this.contentForm.endTime = parseTime(this.msgInfoDate[1])
                }
            },
            submitPrizeHandle(index) {
                const _this = this
                _this.renderMsgDate()
                this.contentForm.activityInfoId = this.json.activityId
                console.log(this.contentForm)
                if (this.msgInfoDate.length !== 0) {
                    this.dataShow = false
                } else {
                    this.dataShow = true
                }
                console.log(this.selction)
                for (var i = 0; i < this.selction.length; i++) {
                    if (this.selction[i].goodsTypeName == this.contentForm.goodsType) {
                        console.log(23123)
                        console.log(this.selction[i])
                        this.contentForm.goodsType = this.selction[i].gtid
                    }
                }
                this.$refs.contentForm.validate(valid => {
                    if (valid) {
                        const scoreEnd = _this.contentForm.scoreEnd
                        const bargainNum = _this.contentForm.bargainNum
                        const exchangeScore = _this.contentForm.exchangeScore
                        const lowestQuotation = _this.contentForm.lowestQuotation
                        const Surplus = exchangeScore - lowestQuotation
                        if (lowestQuotation >= exchangeScore) {
                            _this.$alert('最低价格大于或等于原价', '填写的数据有误', {
                                confirmButtonText: '确定',
                                callback: function (action) {
                                    _this.$message({
                                        type: 'error',
                                        message: '非法操作'
                                    })
                                }
                            })
                        } else if (scoreEnd * bargainNum > Surplus) {
                            _this.$alert('最终砍价金额可能大于或等于商品最低价格', '填写的数据有误', {
                                confirmButtonText: '确定',
                                callback: function (action) {
                                    _this.$message({
                                        type: 'error',
                                        message: '非法操作'
                                    })
                                }
                            })
                        } else if (Surplus <= 0) {
                            _this.$alert('最低金额为0或者小于0', '填写的数据有误', {
                                confirmButtonText: '确定',
                                callback: function (action) {
                                    _this.$message({
                                        type: 'error',
                                        message: '非法操作'
                                    })
                                }
                            })
                        } else {
                            request({
                                url: '/activityConsole/activityBargain/addBargainMessage',
                                method: 'post',
                                data: this.contentForm
                            }).then(res => {
                                console.log(res)
                                const state = res.status === '200' ? 'success' : 'error'
                                if (res.status === '200') {
                                    _this.init()
                                    _this.dialogFormVisible1 = false
                                }
                                _this.$message({
                                    type: state,
                                    message: res.description
                                })
                            }).catch(err => {
                                console.log(err)
                            })
                        }
                    }
                })
            }
        }
    }
</script>
<style scoped>
    .img {
        width: 100%;
    }
</style>

